<?php

class Core_Model_Global_Module extends Dcmp_Model_Entity {

    public function __construct() {
        parent::__construct();
    }

    protected function getTableClass() {
        return Kd_Loader::loadClass('table_global_module');
    }

    public function assignArea(array $areaIds) {
        $this->getTable()
                ->deleteAreaRelation($this->getId())
                ->insertAreaRelation($this->getId(), $areaIds);
    }

    public function loadByName($name) {
        $areaId = App::getAreaSetting()->getId();
        $module = Kd_Data_Factory::getQueryDcl()
                        ->from('{t}global_module', 'a')
                        ->join()->inner('{t}global_module_area', 'b')->on('a.id', 'b.module_id')->closest()
                        ->select()->field('b.area_id', 'area_id')
                        ->closest()
                        ->where()
                        ->eq('name', ':name:s')
                        ->eq('area_id', ':areaId:i')->closest()
                        ->addParameter(array('name' => $name, 'areaId' => $areaId))
                        ->fetch()
                        ->getFirstRow();
        return $module;
    }

    public function getAssignedAreas() {
        return App::getModel('global/collection_area')
                ->innerJoin('{t}global_module_area', 'f', 'f.module_id', 'a.id')
                ->eq('f.module_id', ':moduleId:s')
                ->addParameter('moduleId', $this->getId())
                ->load();
    }

    protected function initializeTable($table) {
        $table->setName('{t}global_module');
        $table->createColumn('id', 'guid', TRUE);
        $table->createColumn('name');
        $table->createColumn('title');
        $table->createColumn('version');
        $table->createColumn('author');
        $table->createColumn('company');
        $table->createColumn('website_uri');
        $table->createColumn('email');
        $table->createColumn('creator_id', 'integer');
        $table->createColumn('created_time', 'datetime')->setDefaultValue(date('Y-m-d H:i:s'));
    }

}
